package com.atguigu.tingshu.search.listener;


import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.config.RabbitConfig;
import com.atguigu.tingshu.common.config.config.RabbitConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.query.search.AlbumInfoIndex;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SearchListener {
    @Resource
    private UserInfoFeignClient userInfoFeignClient;
    @Resource
    private CategoryFeignClient categoryFeignClient;

    @Resource
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.ALBUM_SAVE_QUEUE),
            exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions ="true"),
            key = {RabbitConstant.ALBUM_SAVE_RK}
    ))
    public void saveAlbum(Long albumId, Channel channel, Message message) throws IOException {
        try {

            if (albumId==null){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }

            //执行业务

            AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
            Result<AlbumListVo> albumListVoById = this.albumInfoFeignClient.getAlbumListVoById(albumId);
            if (albumListVoById==null){
                throw new RuntimeException("远程调用根据专辑id获取专辑信息失败");
            }

            AlbumListVo albumListVo = albumListVoById.getData();

            if (albumListVo==null){
                throw new RuntimeException("实时同步失败 专辑信息不存在");
            }


            BeanUtils.copyProperties(albumListVo,albumInfoIndex);
            albumInfoIndex.setId(albumListVo.getAlbumId());
            //根据主播id查询主播
            Result<UserInfo> userInfoById = userInfoFeignClient.getUserInfoById(albumListVo.getUserId());


            if (userInfoById==null||userInfoById.getData()==null){
                throw new RuntimeException("远程调用根据主播id查询用户信息失败");
            }
            albumInfoIndex.setAnnouncerName(userInfoById.getData().getNickname());


            //查询三级分类id
            Result<BaseCategoryView> baseCategoryViewBycategory3Id = categoryFeignClient.getBaseCategoryViewBycategory3Id(albumListVo.getCategory3Id());
            if (baseCategoryViewBycategory3Id==null){
                throw new RuntimeException("远程嗲用查询三级分类信息失败");
            }

            BaseCategoryView baseCategoryView = baseCategoryViewBycategory3Id.getData();

            if (baseCategoryView!=null){
                albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
                albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
            }

            //假数据
            albumInfoIndex.setPlayStatNum(new Random().nextInt(10)*10000);
            albumInfoIndex.setSubscribeStatNum(new Random().nextInt(10)*10000);
            albumInfoIndex.setBuyStatNum(new Random().nextInt(10)*10000);

            albumInfoIndex.setHotScore(albumInfoIndex.getPlayStatNum()*0.1
                    +albumInfoIndex.getSubscribeStatNum()*0.3
                    +albumInfoIndex.getCommentStatNum()*0.2
                    +albumInfoIndex.getBuyStatNum()*0.4);


            //标签属性
            Result<List<AlbumAttributeValue>> albumAttributesByAlbumId = this.albumInfoFeignClient.findAlbumAttributesByAlbumId(albumListVo.getAlbumId());
            if (albumAttributesByAlbumId==null){
                throw new RuntimeException("远程调用查询标签数据失败");

            }
            List<AlbumAttributeValue> albumAttributeValues = albumAttributesByAlbumId.getData();
            if (albumAttributeValues!=null){
                List<AttributeValueIndex> attributeValueIndexList = albumAttributeValues.stream().map(albumAttributeValue -> {
                    AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                    BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                    return attributeValueIndex;
                }).collect(Collectors.toList());

                //设置给albumInfoIndex
                albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);

            }


            this.elasticsearchTemplate.save(albumInfoIndex);

            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);


        }catch (Exception e){
            if (message.getMessageProperties().getRedelivered()){
//                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false );
                //记录日志
                log.error("新增 es同步数据过程消息消费失败，消息的内容"+albumId);
            }else {
                //消费异常 重新入队重试
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }



    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.ALBUM_DEL_QUEUE),
            exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions ="true"),
            key = {RabbitConstant.ALBUM_DEL_RK}
    ))
    public void delAlbum(Long albumId,Channel channel,Message message) throws IOException {
        try {
            if (albumId==null){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }

            //执行业务代码

            this.elasticsearchTemplate.delete(albumId.toString(),AlbumInfoIndex.class);
        }catch (Exception e){

            if (message.getMessageProperties().getRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                log.error("删除es 消费器消费失败"+albumId);
            }else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }


        }




    }
}
